/**
 * Copyright 2006 gworks.com.au
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. (http://www.apache.org/licenses/LICENSE-2.0)
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed 
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for 
 * the specific language governing permissions and limitations under the License.
 *
 * <dhamma-message src="Atisha (11th century Tibetan Buddhist master)">
 * 	The greatest achievement is selflessness. The greatest worth is self-mastery.
 * 	The greatest quality is seeking to serve others. The greatest precept is continual awareness.
 * 	The greatest medicine is the emptiness of everything. The greatest action is not conforming with the worlds ways.
 * 	The greatest magic is transmuting the passions. The greatest generosity is non-attachment.
 * 	The greatest goodness is a peaceful mind. The greatest patience is humility.
 * 	The greatest effort is not concerned with results. The greatest meditation is a mind that lets go.
 * 	The greatest wisdom is seeing through appearances. 
 * </dhamma-message>
 */
package au.com.gworks.jump.app.wiki.server.mockimpl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.javaongems.runtime.io.PathUtils;
import org.javaongems.runtime.util.ListUtils;

import au.com.gworks.jump.app.util.BootstrapPlugin;
import au.com.gworks.jump.io.SystemFailure;
import au.com.gworks.jump.system.ApplicationManager;


public class SystemLoader implements BootstrapPlugin{
	final static public String CONF_DIR = "conf";
	final static public String ENV_PROPERTIES_FILE = "env.properties";
	final static private Logger LOGGER = Logger.getLogger(SystemLoader.class);
	
	private String homePath;

	public void load() throws SystemFailure {
		homePath = verifyHome();
		Properties props = loadEnvironmentPropertiesFile();
		initialiseApplicationInfo(props);
		initialiseResourceExtensionHandling(props);
	}

	private void initialiseApplicationInfo(Properties props) {
		String adminAsStr = props.getProperty("administrators");
		List admins = ListUtils.toList(adminAsStr, ",", true);
		for (Iterator iter = admins.iterator(); iter.hasNext();) {
			String userName = (String) iter.next();
			LOGGER.info("acknowledging admin ->" + userName);
		}
		
		String[] info = new String[10];
		info[4] = props.getProperty("application.systemNamespace");
		info[0] = props.getProperty("application.name");
		initialiseApplInfoWithContentReferences(info[4], props, info);
		info[5] = props.getProperty("application.guestUser");
		info[6] = props.getProperty("application.guestPassword");
		info[7] = props.getProperty("application.defaultEntryNamespace");
		info[8] = props.getProperty("application.mimeTypeProperty");
		info[9] = props.getProperty("application.binaryMimeTypeValue");
		ApplicationManager.init(homePath, admins, info);
	}
	
	private void initialiseResourceExtensionHandling(Properties props) {
		String rawExts = props.getProperty("application.treatAsRawDefaultExtensions");
		String txtExts = props.getProperty("application.treatAsTextDefaultExtensions");
		List rawList = ListUtils.toList(rawExts, ",", true);
		List txtList = ListUtils.toList(txtExts, ",", true);
		ApplicationManager.treatAsRawDefaultExtensions.addAll(rawList);
		ApplicationManager.treatAsTextDefaultExtensions.addAll(txtList);
	}
	
	private void initialiseApplInfoWithContentReferences(String namespace, Properties props, String[] info) {
		FileSystemProvider provider = new FileSystemProvider(namespace, "sys");
		try {
			info[1] = loadResourceContent(provider, "application.bannerPath", props);
			info[2] = loadResourceContent(provider, "application.headPath", props);
			info[3] = loadResourceContent(provider, "application.footerPath", props);
		} finally {
			provider.close();
		}
	}
	
	private String loadResourceContent(FileSystemProvider provider, String name, Properties props) {
		String ret = props.getProperty(name);
		if (ret != null) {
			try {
				ret = provider.openFileAsText(ret);
			} catch (IOException err) {
				LOGGER.error("unable to load boot resource [" + name + "] from " + ret, err);
			}
		}
		return ret;
	}
	
	private Properties loadEnvironmentPropertiesFile() throws SystemFailure {
		Properties env = new Properties();
		String file = PathUtils.appendSlashIfRequired(homePath) + ENV_PROPERTIES_FILE;
		try {
			FileInputStream fis = new FileInputStream(file);
			try {
				env.load(fis);
			} finally {
				fis.close();
			}
		} catch (IOException err) {
			throw new SystemFailure(LOGGER, "unable to load " + ENV_PROPERTIES_FILE, err);
		}
		return env;
	}

	private String verifyHome() throws SystemFailure {
		String temp = System.getProperty("user.dir") + "/../../" + CONF_DIR;
		File testCtx = new File(temp);
		try {
			temp = testCtx.getCanonicalPath();
			testCtx = new File(temp);
		} catch (IOException err) {
			throw new SystemFailure(LOGGER, "unable to get canonical path representation", err);
		}
		if (!testCtx.isDirectory())
			throw new SystemFailure(LOGGER, "Invalid mock home [" + temp + "]. Note, Tomcat should be launched from the tomcat/bin directory", new IllegalStateException("Mock repository"));
		
		String parentPath = testCtx.getParent();
		FileSystemProvider.initialiseHome(parentPath);
		return temp;
	}
}
